package com.nervenets.general.utils;

import com.nervenets.general.exception.LogicException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

/**
 * 文件上传工具类
 *
 * @author somewhere
 */
public class FileUploadUtil {
    /**
     * 默认大小 1024M
     */
    public static long DEFAULT_MAX_SIZE = 1024 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static int DEFAULT_FILE_NAME_LENGTH = 100;

    private static int counter = 0;

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static String upload(String baseDir, MultipartFile file) throws IOException {
        try {
            return upload(baseDir, file, MimeTypeUtil.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws IOException 比如读写文件出错时
     */
    public static String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws IOException {
        if (null == file) throw new LogicException("没有找到文件");
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) throw new LogicException("没有找到上传文件的文件名，请确认参数是否有误。");
        int fileNameLength = originalFilename.length();
        if (fileNameLength > FileUploadUtil.DEFAULT_FILE_NAME_LENGTH) {
            throw new LogicException("文件名长度最大为：" + FileUploadUtil.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);

        String fileName = extractFilename(file);

        File desc = getAbsoluteFile(baseDir, fileName, false);
        file.transferTo(desc);
        return getPathFileName(baseDir, fileName);
    }

    /**
     * 编码文件名
     */
    public static String extractFilename(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = JodaUtils.timeLongToString("yyyyMMdd") + File.separator + encodingFilename(fileName) + "." + extension;
        return fileName;
    }

    private static File getAbsoluteFile(String uploadDir, String fileName, boolean createNewFile) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists() && createNewFile) {
            desc.createNewFile();
        }
        return desc;
    }

    private static String getPathFileName(String uploadDir, String fileName) {
        int dirLastIndex = uploadDir.lastIndexOf(File.separator) + 1;
        String currentDir = StringUtils.isBlank(uploadDir) ? null : uploadDir.substring(dirLastIndex);
        return File.separator + currentDir + File.separator + fileName;
    }

    /**
     * 编码文件名
     */
    private static String encodingFilename(String fileName) {
        fileName = fileName.replace("_", " ");
        fileName = DigestUtils.md5DigestAsHex((fileName + System.nanoTime() + counter++).getBytes());
        return fileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     */
    public static void assertAllowed(MultipartFile file, String[] allowedExtension) {
        long size = file.getSize();
        if (size > DEFAULT_MAX_SIZE) {
            throw new LogicException("最大上传文件大小：" + (DEFAULT_MAX_SIZE / 1024 / 1024) + "MB");
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && allowedExtension.length > 0 && !isAllowedExtension(extension, allowedExtension)) {
            throw new LogicException(String.format("不支持的文件格式 : allowedExtension-%s extension-%s fileName-%s", Arrays.toString(allowedExtension), extension, fileName));
        }

    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtil.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }
}
